package current;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition的等待唤醒
 */
public class ConditionAwait {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        Thread t1 = new Thread(() -> {
            System.out.println("before-wait-1...");
            try {
                // 获取锁
                lock.lock();
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 释放锁
                lock.unlock();
            }
            System.out.println("after-wait-1...");
        });

        Thread t2 = new Thread(() -> {
            System.out.println("before-wait-2...");
            try {
                // 获取锁
                lock.lock();
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 释放锁
                lock.unlock();
            }
            System.out.println("after-wait-2...");
        });

        t1.start();
        t2.start();

        // 非主线程先获取锁，让其可以执行到after-wait
        TimeUnit.MICROSECONDS.sleep(10);

        //信号唤醒,也需要先拿到锁
        lock.lock();
        condition.signalAll();
        lock.unlock();
    }
}
